package com.jiyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiyun.entity.Book;
import com.jiyun.entity.Borrow;
import com.jiyun.entity.BorrowDTO;
import com.jiyun.entity.User;
import com.jiyun.mapper.BookMapper;
import com.jiyun.mapper.BorrowMapper;
import com.jiyun.mapper.UserMapper;
import com.jiyun.service.IBorrowService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-04-19
 */
@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow> implements IBorrowService {

    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    BookMapper bookMapper;

    @Override
    public Page findPage(Page<Borrow> borrowPage,Integer userId) {
        LambdaQueryWrapper<Borrow> qw = new LambdaQueryWrapper<>();
        if (userMapper.selectById(userId).getRoleName().equals("普通用户")) {
            qw.eq(Borrow::getUid,userId);
        }

        borrowMapper.selectPage(borrowPage,qw);

        List<BorrowDTO> list = new ArrayList<>();
        for (Borrow borrow : borrowPage.getRecords()) {
            Integer bid = borrow.getBid();
            Integer uid = borrow.getUid();
            Book book = bookMapper.selectById(bid);
            User user = userMapper.selectById(uid);
            BorrowDTO borrowDTO = new BorrowDTO();
            BeanUtils.copyProperties(borrow,borrowDTO);
            borrowDTO.setBook(book);
            borrowDTO.setUser(user);
            list.add(borrowDTO);
        }

        Page<BorrowDTO> borrowDTOPage = new Page<>(borrowPage.getCurrent(),borrowPage.getSize());
        borrowDTOPage.setTotal(borrowPage.getTotal());
        borrowDTOPage.setRecords(list);
        return borrowDTOPage;
    }
}
